import React, { useEffect, useRef } from 'react';
import { Dialog, Field, Form, Input, NumberPicker, Select, Upload, Grid } from '@alifd/next';
import Standard from './Standard';
import Params from './Params';
import CommodityService from '../../service';
import CategoryService from '@/pages/CommodityCenter/CategoryManage/service';
import BrandService from '@/pages/CommodityCenter/BrandManage/service';
import { useRequest } from 'ice';
import { objectToArray, SelectRequestConfig } from '@/pages/CommodityCenter/CommodityManage/entity';
import st from './index.module.scss';
import { beforeUpload } from '@/utils/ossutil';

const { Row, Col } = Grid;

interface Props {
  visible: boolean;
  row: CommodityState.CommodityItem;
  onRefresh: () => void;
  onClose: () => void;
}

const FormItem = Form.Item;

const CreateDialog: React.FC<Props> = (props) => {
  const field = Field.useField([
    {
      values: {
        paramExtra: [{}],
        attr: { cheched: false },
      },
    },
  ]);
  const { visible, row, onRefresh = () => { }, onClose } = props;

  const { request, loading } = useRequest(CommodityService.createCommodity, {
    onSuccess: () => {
      onRefresh();
      onClose();
    },
  });

  const { data: brandList, request: brandRequest } = useRequest(BrandService.getBrandPage, SelectRequestConfig);

  const { data: categoryList, request: categoryRequest } = useRequest(CategoryService.getCategoryPage, SelectRequestConfig);

  useEffect(() => {
    if (visible && row.id) {
      const images = row.images?.split(',').map((it, i) => ({
        uid: `${i}`,
        state: 'done',
        url: it,
        downloadURL: it,
        imgURL: it,
      })) || [];
      field.setValues({
        ...row,
        createTime: undefined,
        updateTime: undefined,
        brand: { value: row.brandId, label: row.brandName },
        category: { value: row.categoryId, label: row.categoryName },
        attr: !row.attrId ? { checked: false } : { checked: true, propertyId: row.attrId, propertyValues: row.attrName },
        paramExtra: row.paramExtra ? objectToArray(JSON.parse(row.paramExtra)) : [{}],
        images: [{
          uid: '-1',
          state: 'done',
          url: row.mainImage,
          downloadURL: row.mainImage,
          imgURL: row.mainImage,
        }].concat(images),
      });
    }
    if (!visible) {
      field.reset();
    }
  }, [visible]);

  const handleOk = () => {
    field.validate((errors, values): void => {
      if (errors) {
        return;
      }
      const attr = values.attr.checked ? {
        attrId: values.attr.propertyId,
        attrName: values.attr.propertyValues,
      } : {};
      const obj = {};
      values.paramExtra?.filter((it) => !!it.key && !!it.value).forEach((a) => {
        obj[a.key] = a.value;
      });
      const images = values.images?.map(t => t.url);
      request({
        ...values,
        ...attr,
        name: values.name.trim(),
        remark: values.remark?.trim(),
        id: row.id,
        status: row.status || 1,
        brandId: values.brand.value,
        brandName: values.brand.label,
        categoryId: values.category.value,
        categoryName: values.category.label,
        paramExtra: JSON.stringify(obj),
        mainImage: images.slice(0, 1).join(','),
        images: images.slice(1).join(','),
        brand: undefined,
        attr: undefined,
        category: undefined,
      });
    });
  };

  const searchBrand = (val: string) => {
    brandRequest({ current: 1, pageSize: 10 }, { name: val, enable: true });
  };

  const searchCategory = (val: string) => {
    categoryRequest({ current: 1, pageSize: 10 }, { name: val, enable: true });
  };

  const validateImages = (rule, values) => {
    if (!values || values.length < 2) {
      return Promise.reject(new Error('至少上传两张图片'));
    }
    return Promise.resolve();
  };

  return (
    <Dialog
      shouldUpdatePosition
      overflowScroll
      visible={visible}
      onClose={onClose}
      title={`${row.id ? '编辑' : '新增'}商品`}
      style={{ width: 520 }}
      onOk={handleOk}
      okProps={{ loading }}
      onCancel={onClose}
    >
      <Form
        fullWidth
        field={field}
        useLabelForErrorMessage
      >
        <FormItem label="商品名称" name="name" required>
          <Input placeholder="请输入" />
        </FormItem>
        <Row gutter="4">
          <Col>
            <FormItem label="商品品牌" name="brand" required>
              <Select
                showSearch
                filterLocal={false}
                onSearch={searchBrand}
                dataSource={brandList}
                useDetailValue
                placeholder="请输入品牌名称"
              />
            </FormItem>
          </Col>
          <Col>
            <FormItem label="所属分类" name="category" required>
              <Select
                showSearch
                filterLocal={false}
                onSearch={searchCategory}
                dataSource={categoryList}
                useDetailValue
                placeholder="请输入类目名称"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem
          label={(
            <div className={st.formLabel}>
              <p>商品主图：</p>
              <span className={st.tip}>默认第一张为主图，请选择大小不超过5M的文件，支持png/jpg/jpeg/gif格式</span>
            </div>
          )}
          name="images"
          validator={validateImages}
        >
          <Upload.Card
            accept="image/png, image/jpg, image/jpeg, image/gif"
            listType="card"
            withCredentials={false}
            beforeUpload={beforeUpload}
            formatter={(res, file) => ({
              success: true,
              url: file.tempUrl,
            })}
            useDataURL
          />
        </FormItem>
        <FormItem label="市场价" format="number" name="marketPrice" required>
          <NumberPicker hasTrigger={false} min={0} style={{ width: '100%' }} placeholder="请输入" />
        </FormItem>
        <FormItem label={(<div className={st.formLabel}>商品属性<span className={st.tip}>（创建后不能修改）</span></div>)} name="attr">
          <Standard isPreview={!!row.id} defaultValue={{ checked: false }} />
        </FormItem>
        <FormItem label="商品参数" name="paramExtra">
          <Params defaultValue={[{}]} />
        </FormItem>
        <FormItem label="商品描述" name="remark">
          <Input.TextArea showLimitHint maxLength={100} placeholder="请输入商品描述" />
        </FormItem>
      </Form>
    </Dialog>
  );
};

export default CreateDialog;
